
var app = getApp()
var Bmob = require('../../utils/Bmob-2.2.0.min.js');
var util = require('../../utils/util.js');
Page({
  data: {
    isReEdit: false,
    franchiseeId: '',
    appointment:{
      title:'',
      cover:'',
      rangeAddress:'',
      serviceTime: {
        startTime: '00:00',
        endTime: '23:59',
      },
      content:'',
      userId:'',
      hots:0
    },
     serviceType:0,
    serviceText:["水电工","家政保洁","家电维修","跑腿服务","门窗维修","送水"],
    serviceIndex:0,      
    franchiseeInfo: {},
   
  },
  onLoad: function (options) {
   var that=this;
    var skillId=options.skillId;
    let edit = options.edit || '';
    if(typeof(skillId)=='undefined')

    {

    }else{
     that.getSkillDetail(skillId)
      this.setData({
        isReEdit: true,
      });
    } 

 
  },

   // 获取
getSkillDetail:function(skillId){
  var that = this;
  var service = Bmob.Query("appointsment");
  
  service.get(skillId).then(res => {

    that.setData({
      appointment: res
    })


  })


},
  // 完善信息保存
  enterSubmit: function (e) {
    let that = this;
    let val = e.detail.value;
   console.log(val);
     var name=val.name;
     var address_detail = val.address_detail;
     var phone=val.phone;
    var index = that.data.serviceIndex;
    var serviceTime={}
    serviceTime.startTime = val.start_time;
    serviceTime.end_time = val.end_time;
    var description = val.description;
   var cover=that.data.appointment.cover;
 
    if (!name) {
      app.showModal({
        content: '请输入个人姓名'
      });
      return;
    }
    if (!cover) {
      app.showModal({
        content: '请上传本人照片'
      });
      return;
    }
 
    if (!description) {
      app.showModal({
        content: '请输入技能简介'
      });
      return;
    }
    if (!(/^1[3456789]\d{9}$/.test(phone))) {
      that.showLoading("输入正确手机号");
      return;
    }
    var serviceInfo = Bmob.Query("appointsment");
    serviceInfo.set("name",name);
    serviceInfo.set("cover",cover);
    serviceInfo.set("rangAddress", address_detail);
    serviceInfo.set("serviceType", index);
    serviceInfo.set("phone", phone);
    serviceInfo.set("content", description);
    serviceInfo.set("serviceTime", serviceTime);
    serviceInfo.set("status",1);
  serviceInfo.save().then(res=>{
    console.log(res);
  })
  },
  // 上传照片
  uploadLicenseImg: function (e) {
    let that = this;
    let length = e.currentTarget.dataset.length || 6;
    let field = e.currentTarget.dataset.field;
    let num = length - that.data[field].length;
    app.chooseImage(function (res) {
      console.log(res);
      let newdata = {};
      newdata[field] = that.data[field].concat(res);
      that.setData(newdata);
    }, num);
  },
  // 删除照片
  deleteLicenseImg: function (e) {
    let index = e.currentTarget.dataset.index;
    let field = e.currentTarget.dataset.field;
    let img = this.data[field];

    img.splice(index, 1);
    let newdata = {};
    newdata[field] = img;
    this.setData(newdata);
  },
  // 营业时间-开始
  bindStartTimeChange: function (e) {
    this.setData({
      startTime: e.detail.value
    })
  },
  // 营业时间-结束
  bindEndTimeChange: function (e) {
    this.setData({
      endTime: e.detail.value
    })
  },

  // 预览图片
  previewImage: function (e) {
    let src = e.currentTarget.dataset.src;

    app.previewImage({
      current: src
    });
  },
  // 选择模板弹窗显示
  tplPopShow: function () {
    this.setData({
      tplHidden: false
    });
  },

  // 模板详情弹窗显示
  tplDetailShow: function (e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      tplDetailHidden: false,
      tplId: id
    });
  },
 
  
  // 上传logo

  uploadLogo: function () {
    var that = this;
    wx.chooseImage({
      success: function (res) {

        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths)
        var file;
        for (let item of tempFilePaths) {
          console.log('item', item)
          file = Bmob.File('abc.jpg', item);
          console.log(file)
        }
        console.log(file)
        file.save().then(res => {
          console.log(res.length);
          console.log(res[0].url);
          that.setData({
            'appointment.cover': res[0].url
          })
        })

      }
    })
  },
  
  
  
  // 行业分类选择器改变
  bindIndustryChange: function (e) {
    this.setData({
       serviceIndex: e.detail.value
    })
  },
  // 店铺分类选择器改变
  bindCategoryChange: function (e) {
    this.setData({
      categoryIndex: e.detail.value
    })
  },
  // 获取行业分类
  getIndustryType: function (successfn) {
    let that = this;

    app.sendRequest({
      url: '/index.php?r=AppShop/GetIndustryAndBussinessType',
      data: {
      },
      success: function (res) {
        let industry = res.data.industry;
        let cate = [];
        for (let i in industry) {
          cate.push({
            id: i,
            name: industry[i]
          });
        }
        that.setData({
          industryList: cate
        });
        typeof successfn === 'function' && successfn(res);
      }
    });
  },
  
  // 重新编辑保存
  reEditSubmit: function (e) {
    let that = this;
    let val = e.detail.value;
    let franchiseeId = that.data.franchiseeId;
   
    var name = val.name,
      phone = val.phone,
      address_detail = val.address_detail,
      business_time = [{
        start_time: val.start_time,
        end_time: val.end_time
      }],
      description = val.description,
      address = {},
      businesstime = [],
      regionList = that.data.regionList,
      region = that.data.region,
      per_capita = val.per_capita;

    var picture = that.data.shopLogo;
    var category = that.data.categoryIndex;
    var longitude = that.data.longitude;
    var latitude = that.data.latitude;
    var county_id = that.data.regionList[2][that.data.region[2]].id;
    var carousel_imgs = that.data.shopImg;

    if (!name) {
      app.showModal({
        content: '请输入店铺名称'
      });
      return;
    }
    if (!picture) {
      app.showModal({
        content: '请上传店铺logo'
      });
      return;
    }
    if (!longitude) {
      app.showModal({
        content: '请去定位一下店铺位置'
      });
      return;
    }
    if (!address_detail) {
      app.showModal({
        content: '请填写详细地址'
      });
      return;
    }
    if (!phone) {
      app.showModal({
        content: '请输入门店客服电话'
      });
      return;
    }
    if (!/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/.test(phone) && !/^(\d{3,4}-?)?\d{7,8}$/.test(phone)) {
      app.showModal({
        content: '请输入正确的客服电话'
      });
      return;
    }
  
    if (that.data.categoryList.length > 0 && category.length <= 0) {
      app.showModal({
        content: '请选择店铺分类'
      });
      return;
    }
    if (!description) {
      app.showModal({
        content: '请输入门店介绍'
      });
      return;
    }
    if (!carousel_imgs.length) {
      app.showModal({
        content: '请上传店铺环境图片'
      });
      return;
    }
    if (per_capita && (!/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(per_capita))) {
      app.showModal({
        content: '请输入正确的人均消费'
      });
      return;
    }
    address.province_name = regionList[0][region[0]].name;
    address.city_name = regionList[1][region[1]].name;
    address.county_name = regionList[2][region[2]].name;
    address.detail = address_detail;
    var time = {}
    time.start_time = that.data.startTime;
    time.end_time = that.data.endTime;
    businesstime.push(time);
    var Franchisee = Bmob.Object.extend("Franchisee");
    var franchisee = new Bmob.Query(Franchisee);
    var currentUser = Bmob.User.current();
    var objectId = currentUser.id;
    var isme = new Bmob.User();
    isme.id = objectId;

    franchisee.get(franchiseeId, {
      success: function (result) {
        console.log("fjdksljal")
        // 回调中可以取得这个 GameScore 对象的一个实例，然后就可以修改它了
        result.set("Franchisee_title", name);
        result.set("Franchisee_phone", phone);
        result.set("Franchisee_address", address);
        result.set("img_url", picture);
        result.set("Franchisee_type", that.data.categoryList[category].category);
        result.set("business_time", businesstime);
        result.set("longitude", longitude);
        result.set("latitude", latitude);
        result.set("description", description);
        result.set("per_capita", per_capita);
        result.set("carousel_imgs", carousel_imgs);
        result.set("is_audit", 1);
        result.set("user", isme);
        result.set("hot", 0);
        result.save(null, {
          success(res) {
            app.showToast({
              title: '保存成功',
              icon: 'success'
            });

            app.turnToPage("/pages/franchiseeEnterStatus/franchiseeEnterStatus?franchisee_id=" + that.data.franchiseeId, true);
          }


        });

        // The object was retrieved successfully.
      },
      error: function (error) {
        console.log(error)
      }
    });
   
  },
  // 获取旧数据
  getSubShopData: function () {
    var that = this;
    var Franchisee = Bmob.Object.extend("Franchisee");
    var franchisee = new Bmob.Query(Franchisee);
    var franchiseeId = that.data.franchiseeId;



    franchisee.get(franchiseeId, {
      success: function (res) {
        //var goods=res;
        let categoryList = that.data.categoryList;
        let category = res.get("Franchisee_type") ? res.get("Franchisee_type") : 0;
        var categoryIndex;
        for (let i = 0; i < categoryList.length; i++) {
          if (categoryList[i].category == category) {
            categoryIndex = i;
            break;
          }
        }
        var business_time = res.get("business_time");
        var franchisee_address = res.get("Franchisee_address");
        that.setData({
          franchiseeInfo: res,
          address: franchisee_address.detail,
          shopLogo: res.get("img_url"),
          category: res.get("Franchisee_type"),
          longitude: res.get("longitude"),
          latitude: res.get("latitude"),
          categoryIndex: categoryIndex,
          shopImg: res.get("carousel_imgs"),
          startTime: business_time && business_time.length ? business_time[0].start_time : '00:00',
          endTime: business_time && business_time.length ? business_time[0].end_time : '23:59'
        })
        that.getArea(function () {
          that.textToRegion(res.get("Franchisee_address").province_name, res.get("Franchisee_address").city_name, res.get("Franchisee_address").county_name);
        });

      },
      complete: function () {

      }
    });

   
  },
 
  // 拨打电话
  makePhoneCall: function (e) {
    var phone = e.currentTarget.dataset.phone;
    app.makePhoneCall(phone);
  },

})
